package com.example.shiwu.util;

import static com.example.shiwu.util.ContextVariable.DOWN_NAME;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.documentfile.provider.DocumentFile;

import com.alibaba.fastjson2.support.csv.CSVWriter;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.service.ItemsService;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

public class FileDownUtil {
    public static final String DOWNLOAD_PATH = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/shiwu/";//将文件下载到Down/shiwu下
    public static final String DOWN_NAME = "/data/data/com.example.shiwu/files/";
    public static final String DOWN_SHIWU = "/data/data/com.example.shiwu/shiwu";
    public static final String DOWN_ELE_NAME = "/data/data/com.example.shiwu/files/electrode";
    private static ItemsService itemsService;

    private static String strUrl = "content://com.android.externalstorage.documents/tree/primary%3ADownload%2Fshiwu";

    public static Boolean downLoadFile(Context context, String fileName, String downName, String itemName) {

        Boolean bool = false;
        InputStream inputStream = null;
        File files = new File(fileName);
        try {
            inputStream = new FileInputStream(files);
            if(inputStream == null){
                return false;
            }
            //System.out.println(context.getExternalFilesDir(null));
            System.out.println(DOWNLOAD_PATH);

            String itmeFile = DOWNLOAD_PATH + itemName;
            File downloadFile = new File(DOWNLOAD_PATH);
            File downloadItemFile = new File(DOWNLOAD_PATH + itemName);
            if (!downloadFile.exists()) {
                downloadFile.mkdir();
            }
            if (!downloadItemFile.exists()) {
                downloadItemFile.mkdir();
            }

            File file = new File(itmeFile, downName);
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
            bool = true;
        } catch (IOException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
        }
        return bool;
    }

    public static Boolean createShiwuFile() {

        Boolean bool = false;
        File files = new File(DOWN_SHIWU);
        if (!files.exists()) {
            files.mkdir();
        }
        bool = true;
        return bool;
    }

    /**
     * 在download目录下创建加密文件
     * @return
     */
    public static Boolean createDownLoadFile(Context context) throws FileNotFoundException {
        String downloadUriStr = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)+"/shiwu1").substring(1);
        //直接解析路径字符串（需确保路径格式正确）
       // Uri uri = Uri.parse("file://" + downloadUriStr);
        Uri uri = Uri.fromFile(new File(downloadUriStr)); // 低版本
        // 通过 SAF 获取 Download 文件夹的 URI
        Uri downloadUri = DocumentsContract.buildDocumentUriUsingTree(
                Uri.parse(strUrl),
                DocumentsContract.getTreeDocumentId(uri)
        );

        // 创建加密文件夹
        Uri encryptedFolderUri = DocumentsContract.createDocument(
                context.getContentResolver(),
                downloadUri,
                DocumentsContract.Document.MIME_TYPE_DIR,
                "shiwu1"
        );
        return true;
    }

    /**
     * 1.先压缩文件为zip
     * 2.下载zip文件
     * @param context
     * @param fileName
     * @param downName
     * @param itemName
     * @return
     */
    public static Boolean downLoadZipFile(Context context, String fileName, String downName,String downNameNew, String itemName) {

        Boolean bool = false;
        try {
            //压缩
            if(!isZipFile(new File(fileName + ".zip"))){
                zip(fileName,fileName+".zip");
            }

            downLoadZipToDocument(fileName,downName,downNameNew,itemName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bool;
    }
    public static boolean isZipFile(File file) {
        // 检查文件是否存在且是一个文件
        if (!file.exists() || !file.isFile()) {
            return false;
        }

        try (ZipFile zipFile = new ZipFile(file)) {
            // 如果能够成功创建 ZipFile 实例，则说明是有效的 ZIP 文件
            return true;
        } catch (IOException e) {
            // 捕获异常，说明不是有效的 ZIP 文件
            return false;
        }
    }
    public static Boolean downLoadZipToDocument(String fileName, String downName,String downNameNew, String itemName) {

        Boolean bool = false;
        InputStream inputStream = null;
        File files = new File(fileName+".zip");
        try {
            inputStream = new FileInputStream(files);
            if(inputStream == null){
                return false;
            }
            //System.out.println(context.getExternalFilesDir(null));
            System.out.println(DOWNLOAD_PATH);

            String itmeFile = DOWNLOAD_PATH + itemName;
            File downloadFile = new File(DOWNLOAD_PATH);
            File downloadItemFile = new File(DOWNLOAD_PATH + itemName);
            if (!downloadFile.exists()) {
                downloadFile.mkdir();
            }
            if (!downloadItemFile.exists()) {
                downloadItemFile.mkdir();
            }

            File file = new File(itmeFile, downNameNew);
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
            //renameFile(downName,downNameNew);
            bool = true;
        } catch (IOException e) {
            //throw new RuntimeException(e);
            e.printStackTrace();
        }
        return bool;
    }

    public static void renameFile(String oldName, String newName) {
        File file = new File(oldName);
        File newFile = new File(newName);
        if (file.renameTo(newFile)) {
            System.out.println("File name changed successfully");
        } else {
            System.out.println("Failed to change file name");
        }
    }
    /**
     * 删除文件，可以是文件或文件夹
     *
     * @param delFile 要删除的文件夹或文件名
     * @return 删除成功返回true，否则返回false
     */
    public static boolean delete(String delFile) {
        File file = new File(delFile);
        if (!file.exists()) {
//            Toast.makeText(HnUiUtils.getContext(), "删除文件失败:" + delFile + "不存在！", Toast.LENGTH_SHORT).show();
            Log.e("--Method--", "删除文件失败:" + delFile + "不存在！");
            return false;
        } else {
            if (file.isFile())
                return deleteSingleFile(delFile);
            else
                return deleteDirectory(delFile);
        }
    }

    /**
     * 删除单个文件
     *
     * @param filePath$Name 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
                Log.e("--Method--", "删除单个文件" + filePath$Name + "失败！");
                return false;
            }
        } else {
            Log.e("--Method--", "删除单个文件失败：" + filePath$Name + "不存在！");
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param filePath 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator))
            filePath = filePath + File.separator;
        File dirFile = new File(filePath);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            Log.e("--Method--", "删除目录失败：" + filePath + "不存在！");
            return false;
        }
        boolean flag = true;
        // 删除文件夹中的所有文件包括子目录
        File[] files = dirFile.listFiles();
        for (File file : files) {
            // 删除子文件
            if (file.isFile()) {
                flag = deleteSingleFile(file.getAbsolutePath());
                if (!flag)
                    break;
            }
            // 删除子目录
            else if (file.isDirectory()) {
                flag = deleteDirectory(file
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            Log.e("--Method--", "删除目录失败！");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            Log.e("--Method--", "Copy_Delete.deleteDirectory: 删除目录" + filePath + "成功！");
            return true;
        } else {
            Log.e("--Method--", "删除目录：" + filePath + "失败！");
            return false;
        }
    }

    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public static void saveFile(Context context, String[] vel, String simpleUUID) {

        String content = "";
        FileOutputStream fos = null;
        try {
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = context.openFileOutput(getFileName(simpleUUID), Context.MODE_APPEND);
            String content1 = vel[0];
            if (!content1.equals("") && content1.length() > 0) {
                fos.write(content1.getBytes());
                //fos.write("\r\n".getBytes());//写入换行
            }

            for (int i = vel.length - 1; i >= 0; i--) {//cvs数据
                if (i > 0) {
                    if (!vel[i].contains("\n")) {
                        content = vel[i];
                    } else {
                        content = vel[i].substring(1);
                    }
                    fos.write(content.getBytes());
                    fos.write("\r\n".getBytes());//写入换行
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public static Integer saveFileNew(Context context, String[] vel, String name, Integer cvs_line,String itmeName) {

        String content = "";
        FileOutputStream fos = null;
        File file = new File(DOWN_NAME+itmeName);

        try {
            if(vel.length>0){
                if(!file.exists()){
                    boolean isDirCreated = file.mkdir();
                    if (!isDirCreated) {
                        Log.e("FileError", "Failed to create directory");
                    }
                }
                // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
                fos = context.openFileOutput(name, Context.MODE_APPEND);
                if(cvs_line ==0){
                    fos.write(ContextVariable.vol_ele.getBytes());
                    fos.write("\r\n".getBytes());//写入换行
                }

                int len = vel.length;
                if (len > 0) {
//                for (int i = len - 1; i >= 0; i--) {//cvs数据
//                    content = vel[i];
//                    fos.write(content.getBytes());
//                    //fos.write("\r\n".getBytes());//写入换行
//                }
                    for (int i = 0; i < len; i++) {//cvs数据
                        content = vel[i];
                        fos.write(content.getBytes());
                        //fos.write("\r\n".getBytes());//写入换行
                    }
                }
                cvs_line=1;
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    // 设置文件为可读可写
                    file.setReadable(true, false); // 第二个参数为是否仅对所有者有效
                    file.setWritable(true, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return cvs_line;
    }
    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public static Integer saveFileRms(Context context, String[] vel, String name, Integer cvs_line,String itmeName) {

        String content = "";
        FileOutputStream fos = null;
        File file = new File(DOWN_NAME+itmeName);

        try {
            if(!file.exists()){
                boolean isDirCreated = file.mkdir();
                if (!isDirCreated) {
                    Log.e("FileError", "Failed to create directory");
                }
            }
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = context.openFileOutput(name, Context.MODE_APPEND);
            if(cvs_line ==0){
                fos.write(ContextVariable.vol_rms_ele.getBytes());
                fos.write("\r\n".getBytes());//写入换行
            }

            int len = vel.length;
            if (len > 0) {
//                for (int i = len - 1; i >= 0; i--) {//cvs数据
//                    content = vel[i];
//                    fos.write(content.getBytes());
//                    //fos.write("\r\n".getBytes());//写入换行
//                }
                for (int i = 0; i < len; i++) {//cvs数据
                    content = vel[i];
                    fos.write(content.getBytes());
                    //fos.write("\r\n".getBytes());//写入换行
                }
            }
            cvs_line=1;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    // 设置文件为可读可写
                    file.setReadable(true, false); // 第二个参数为是否仅对所有者有效
                    file.setWritable(true, false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return cvs_line;
    }

    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public static Map<String,Integer> saveFileNew(Context context, String[] vel, String name, Integer cvs_line,Integer csv_line_count) {

        String content = "";
        FileOutputStream fos = null;
        Map<String,Integer> map = new HashMap<>();
        try {
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = context.openFileOutput(name, Context.MODE_APPEND);
            if(cvs_line ==0){
                fos.write(ContextVariable.vol_ele.getBytes());
                fos.write("\r\n".getBytes());//写入换行
            }

            int len = vel.length;
            if (len > 0) {
//                for (int i = len - 1; i >= 0; i--) {//cvs数据
//                    content = vel[i];
//                    fos.write(content.getBytes());
//                    //fos.write("\r\n".getBytes());//写入换行
//                }
                for (int i = 0; i < len; i++) {//cvs数据
                    content = vel[i];
                    fos.write(content.getBytes());
                    csv_line_count++;
                    //fos.write("\r\n".getBytes());//写入换行
                }
            }
            cvs_line=1;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        map.put("cvs_line",cvs_line);
        map.put("csv_line_count",csv_line_count);
        return map;
    }
    // 追加文本到指定文件
    public static Map<String,Integer> appendToFile(String[] vel, String name, Integer cvs_line,Integer csv_line_count) {
        String content = "";
        Map<String,Integer> map = new HashMap<>();
        File file = new File(DOWN_NAME+name);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, true);// true 表示追加模式
            if(cvs_line ==0){
                fos.write(ContextVariable.vol_ele.getBytes());
                fos.write("\r\n".getBytes());//写入换行
            }
            int len = vel.length;
            if (len > 0) {
                for (int i = 0; i < len; i++) {//cvs数据
                    content = vel[i];
                    fos.write(content.getBytes());

                    csv_line_count++;
                }
                fos.flush(); // 确保数据写入磁盘
            }
            cvs_line=1;
        } catch (IOException e) {
            e.printStackTrace();
        }if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        map.put("cvs_line",cvs_line);
        map.put("csv_line_count",csv_line_count);
        return map;
    }
    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public static Boolean saveFileNew(Context context, String vel, String name) {
        boolean bl = false;
        FileOutputStream fos = null;
        try {
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = context.openFileOutput(name, Context.MODE_APPEND);
            fos.write(vel.getBytes());
            fos.write("\r\n".getBytes());//写入换行
            bl = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bl;
    }

    /**
     * get file name such as 20171031.txt
     *
     * @return
     */
    public static String getFileName(String simpleUUID) {
        Items items = findSelectItem();
        return items.getId() + "-" + simpleUUID;
    }

    /**
     * get file name such as 20171031.txt
     *
     * @return
     */
    public static String getFileNameNew() {
        Items items = findSelectItem();
        return items.getName();
    }

    public static Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        items.setStatus(1);
        List<Items> lis = itemsService.getItems(items);
        return lis.get(0);
    }
    public static boolean MakeFile(String fileNames) {
        File file = new File(DOWN_NAME+fileNames);
        boolean bl = true;
        if (!file.exists()) {
            boolean isDirCreated = file.mkdir();
            Log.e("FileSuccess", "Success to create directory 0000000000000");
            if (!isDirCreated) {
                bl = false;
                Log.e("FileError", "Failed to create directory");
            }
        }
        return bl;
    }

    /**
     * 压缩文件为gz
     *
     * @param itmeName
     * @param fileNames
     */
    public static void GZIPFile(String itmeName, String fileNames) {
        String gzipFile = DOWN_NAME+itmeName+ "/" +itmeName + "_" + DateUtils.parseYmdHmsDate() +".gz";
        System.out.println("fileNames ================ "+fileNames);
        //String delFileNames = fileNames.substring(fileNames.indexOf("/"),fileNames.length());
        String delFileNames = fileNames;
        File file = new File(DOWN_NAME+itmeName);

        if (!file.exists()) {
            boolean isDirCreated = file.mkdir();
            Log.e("FileSuccess", "Success to create directory 1111111111111111");
            if (!isDirCreated) {
                Log.e("FileError", "Failed to create directory");
            }
        }
        try (GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(gzipFile));
             FileInputStream fis = new FileInputStream(DOWN_NAME+fileNames)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                gzos.write(buffer, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("GZIP压缩完成！");
        deleteFile(delFileNames);
        System.out.println("GZIP压缩完成,删除cvs文件。");
    }

    /**
     * 压缩文件为gz
     *
     * @param itmeName
     * @param fileNames
     */
    public static void GZIPRmsFile(String itmeName, String fileNames) {
        String gzipFile = DOWN_NAME+itmeName+ "/" +"RMS_" +itmeName + "_" + DateUtils.parseYmdHmsDate() +".gz";

        try (GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(gzipFile));
             FileInputStream fis = new FileInputStream(DOWN_NAME+fileNames)) {

            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                gzos.write(buffer, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("GZIP压缩完成！");
        deleteFile(fileNames);
        System.out.println("cvs文件=========="+fileNames);
        System.out.println("GZIP压缩完成,删除cvs文件。");
    }
    public static void deleteFile(String sourceFile) {
        File file =  null;
        if(sourceFile.contains(DOWN_NAME)){
            file = new File(sourceFile);
        }else {
            file = new File(DOWN_NAME+sourceFile);
        }

        if (file.delete()) {
            System.out.println("文件删除成功");
        } else {
            System.out.println("文件删除失败（可能不存在或权限不足）");
        }
    }

    /**
     * 读取文件大小
     * @param sourceFile
     */
    public static long readFileSize(String sourceFile) {
        String name = DOWN_NAME+sourceFile;
        //System.out.println("readFileSize ======= "+name);
        File file = new File(name);
        long fileSizeInBytes = file.length();
        if (file.exists() && file.isFile()) {
            //System.out.println("文件大小（字节）: " + fileSizeInBytes);
            fileSizeInBytes = fileSizeInBytes/ (1024 * 1024);
            //System.out.println("文件大小（B）: " + fileSizeInBytes);

//            System.out.println("文件大小（KB）: " + fileSizeInBytes / 1024);
            //System.out.println("文件大小（MB）: " + fileSizeInBytes / (1024 * 1024));
        } else {
            System.out.println("文件不存在或路径指向目录");
        }
        return fileSizeInBytes;
    }

    /**
     * 读取文件大小
     * @param sourceFile
     */
    public static long readRmsFileSize(String sourceFile) {
        String name = DOWN_NAME+sourceFile;
        //System.out.println("readFileSize ======= "+name);
        File file = new File(name);
        long fileSizeInBytes = file.length();
        if (file.exists() && file.isFile()) {
            //System.out.println("文件大小（字节）: " + fileSizeInBytes);
            fileSizeInBytes = fileSizeInBytes/1024;
            //System.out.println("文件大小（B）: " + fileSizeInBytes);

//            System.out.println("文件大小（KB）: " + fileSizeInBytes / 1024);
            //System.out.println("文件大小（MB）: " + fileSizeInBytes / (1024 * 1024));
        } else {
            System.out.println("文件不存在或路径指向目录");
        }
        return fileSizeInBytes;
    }
    /**
     * 压缩文件或文件夹，包括空文件夹
     *
     * @param srcPath  要压缩的文件或文件夹路径
     * @param zipPath  生成的ZIP文件路径
     * @throws IOException 如果发生I/O错误
     */
    public static void zip(String srcPath, String zipPath) throws IOException {

        try {
            FileOutputStream fos = new FileOutputStream(zipPath);
            ZipOutputStream zos = new ZipOutputStream(fos);

            File folder = new File(srcPath);
            File[] files = folder.listFiles();
            if(null != files){
                for (File file : files) {
                    if (file.isFile()) {
                        addToZip(file, zos, srcPath);
                    } else if (file.isDirectory()) {
                        addToZip(file, zos, srcPath);
                    }
                }

                zos.close();
                fos.close();
            }


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void addToZip(File file, ZipOutputStream zos, String sourceFolder) throws IOException {
        if (file.isHidden()) {
            return;
        }

        String filePath = file.getAbsolutePath();
        int index = filePath.indexOf(sourceFolder);
        String entryName = filePath.substring(index + sourceFolder.length() + 1);

        if (file.isFile()) {
            FileInputStream fis = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(entryName);
            zos.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zos.write(bytes, 0, length);
            }

            fis.close();
        } else if (file.isDirectory()) {
            ZipEntry zipEntry = new ZipEntry(entryName + "/");
            zos.putNextEntry(zipEntry);
            zos.closeEntry();

            File[] children = file.listFiles();
            for (File child : children) {
                addToZip(child, zos, sourceFolder);
            }
        }
    }

    /**
     * 移动文件到指定目录
     * @param sourcePath
     * @param destinationPath
     * @param context
     * @return
     */
    public static boolean moveFile(String sourcePath, String destinationPath, Context context) {
        File sourceFile = new File(sourcePath);
        File destinationFile = new File(destinationPath);
        boolean isMoved = sourceFile.renameTo(destinationFile);
        if (isMoved) {
            Log.d("FileMove", "文件移动成功！");
        } else {
            Log.e("FileMove", "文件移动失败！");
        }
        return isMoved;
    }

    // 方法2: 直接合并GZ流 (仅适用于相同压缩参数的文件)
    public static void mergeByConcatenate(String[] inputFiles,String fileName, String outputFile) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(outputFile)) {
            for (String inputFile : inputFiles) {
                if(inputFile.contains(".gz")){
                    try (FileInputStream fis = new FileInputStream(DOWN_NAME+fileName+"/"+inputFile)) {
                        byte[] buffer = new byte[8192];
                        int bytesRead;

                        // 跳过每个GZ文件的头部 (10字节)
                        //fis.skip(10);

                        // 复制内容 (不包括最后8字节的CRC和大小信息)
                        long fileSize = new File(DOWN_NAME+fileName+"/"+inputFile).length();
                        long bytesToCopy = fileSize; // 减去头部10字节和尾部8字节

                        while (bytesToCopy > 0) {
                            int bytesThisRead = (int) Math.min(buffer.length, bytesToCopy);
                            bytesRead = fis.read(buffer, 0, bytesThisRead);
                            if (bytesRead == -1) break;
                            fos.write(buffer, 0, bytesRead);
                            bytesToCopy -= bytesRead;
                        }

                        // 跳过最后的CRC和大小信息
                        //fis.skip(8);
                    }
                }

            }
        }
    }

    // 获取内部存储沙盒文件列表
    public static List<File> getInternalFiles(Context context,String name) {
        List<File> fileList = new ArrayList<>();
        File dir = context.getFilesDir(); // 获取内部存储应用目录

        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        fileList.add(file);
                    }else if (file.isDirectory()) {
                        System.out.println("这是目录");
                        for (File file1 : files) {
                            if(file1.getName().equals("1-78ba73d4406048bd98de17b27d459848")){
                                fileList.add(file1);
                            }

                        }
                    }
                }
            }
        }
        return fileList;
    }
    // 读取内部存储指定文件夹中的所有文件
    public static List<File> getInternalFilesNew(Context context, String folderName) {
        List<File> fileList = new ArrayList<>();
        // 获取内部存储中的文件夹（不存在则创建）
        File folder = new File(context.getFilesDir(), folderName);

        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        fileList.add(file);
                    }
                }
            }
        }
        return fileList;
    }

    // 获取外部存储沙盒文件列表
    public static List<File> getExternalFiles(Context context) {
        List<File> fileList = new ArrayList<>();
        File dir = context.getExternalFilesDir(null); // 获取外部存储应用专属目录

        if (dir != null && dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isFile()) {
                        fileList.add(file);
                    }
                }
            }
        }
        return fileList;
    }

    /**
     * 在SD卡上创建隐藏文件夹（以.开头）
     * @param context 上下文对象（如Activity）
     * @param sdCardUri 通过SAF获取的SD卡根目录Uri
     */
    public static void createHiddenFolderOnSdCard(Context context) {
        String downloadUriStr = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)).substring(1);
        Uri uri = FileProvider.getUriForFile(context,"com.example.shiwu.provider",new File(downloadUriStr));
        //Uri uri = Uri.fromFile(new File(downloadUriStr)); // 低版本
        // 获取SD卡根目录的DocumentFile（适配分区存储）
        DocumentFile sdCardRoot = DocumentFile.fromTreeUri(context, uri);
        if (sdCardRoot == null) {
            return; // 若获取失败，直接返回
        }

        // 隐藏文件夹名称（以.开头，实现隐藏效果）
        String hiddenFolderName = ".shiwu1";

        // 检查文件夹是否已存在
        DocumentFile existingFolder = sdCardRoot.findFile(hiddenFolderName);
        if (existingFolder != null && existingFolder.isDirectory()) {
            // 文件夹已存在
            Toast.makeText(context, "隐藏文件夹已存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建隐藏文件夹
        DocumentFile newHiddenFolder = sdCardRoot.createDirectory(hiddenFolderName);
        if (newHiddenFolder != null) {
            // 创建成功
            Toast.makeText(context, "隐藏文件夹创建成功", Toast.LENGTH_SHORT).show();
        } else {
            // 创建失败（通常是权限不足）
            Toast.makeText(context, "创建失败，可能缺少权限", Toast.LENGTH_SHORT).show();
        }
    }
    // 检查外部存储是否可读取
    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }

//    public static void saveCsv(String csvFilePath,String[] row) {
//
//        try (Writer writer = new FileWriter(csvFilePath);
//             CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
//                     .withHeader(ContextVariable.vol_rms_ele)
//                     .withDelimiter(',')
//                     .withRecordSeparator("\n"))) {
//
//            // 写入数据行
//            csvPrinter.printRecord(row);
//
//            csvPrinter.flush();
//            System.out.println("CSV文件生成成功！");
//        } catch (IOException e) {
//            System.out.println("生成CSV文件时出错: " + e.getMessage());
//            e.printStackTrace();
//        }
//    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static Boolean saveWithMediaStore(Context context, List<Object> list, String fileName, String itemName) {
        boolean bo = false;
        Gson gson = new Gson();
        String content = gson.toJson(list);
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, fileName);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS+"/shiwu/"+itemName);

        ContentResolver resolver = context.getContentResolver();
        Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);

        if (uri != null) {
            try (OutputStream output = resolver.openOutputStream(uri);
                 OutputStreamWriter writer = new OutputStreamWriter(output)) {
                writer.write(content);
                bo = true;
                //Toast.makeText(this, "文件已保存到 Download+"+"/shiwu/"+itemName+" 目录", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                //Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        return bo;
    }

    public static void fileOver(){
        String content = "jnsdfoghoisdfhgiosdfjgosdfjiogjiodsfjgiodsjfgiojdfogjfd";
        File file = new File(DOWN_NAME+"123.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, true);
            fos.write(content.getBytes()); // 写入内容
            fos.flush(); // 确保数据写入磁盘
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//        String[] boxId = {"01","02","03","04","05","06","07","08","09","10"};
//        //String[] boxlis = {"1","2","3","4","5","6","7","8","9","10","11","12"};
//        List<String> result = new ArrayList<>();
//        for (int y = 0; y < boxId.length; y++) {
//            for (int i = 0; i < 11; i++) {
//                String boxAb = boxId[y]+":"+i+";"+boxId[y]+":"+(i + 1);
//                result.add(boxAb);
//            }
//        }
        int a = 1000000000;

    }

}
